package com.ruoyi.common.utils.file;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.AiBaseInfoConfig;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 文件分块工具类
 */
@Slf4j
public class ChunkUtils {


    /**
     * 清洗文本内容(固定长度拆分)
     *
     * @param template 文本模板，包含需要处理的文本结构
     * @return 返回处理后的文本
     */
    public static List<String> fixedSegment(String template, int tokenLength) {

        List<String> result = new ArrayList<>();
        if (template == null || template.isEmpty()) {
            return result;
        }

        if (tokenLength == 0) {
            tokenLength = 800;
        }
        int step = (int) (tokenLength * (1 - 0.2));
        for (int i = 0; i < template.length(); i += step) {
            int end = Math.min(i + tokenLength, template.length());
            result.add(template.substring(i, end));
        }

        return result;
    }

    /**
     * 正则表达式进行文档分块
     *
     * @param content    文档信息
     * @param sliceRegex 分隔符
     */
    public static List<String> regexChunking(String content, String sliceRegex) {
        List<String> segments = new ArrayList<>();
        if (StringUtils.isBlank(sliceRegex)) {
            // 如果分隔符为空，将整个文档作为一个段落
            segments.add(content);
        } else {
            // 将普通字符串转换为正则表达式模式
            // 使用Pattern.quote确保特殊字符被正确转义
            String regex = Pattern.quote(sliceRegex);

            // 使用正则表达式分割文档内容
            String[] parts = content.split(regex);

            // 添加非空段落
            for (String part : parts) {
                if (!part.trim().isEmpty()) {
                    segments.add(sliceRegex + part.trim());
                }
            }

            // 如果没有分段，则将整个文档作为一个段落
            if (segments.isEmpty()) {
                segments.add(content);
            }
        }
        return segments;
    }


    /**
     * 百炼的语义切片
     *
     * @param template 原文
     * @return 切片结果
     * @throws IOException io异常
     */
    public static List<JSONObject> getDocumentSplitByHttpRequest(String template) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            String documentSplitUrl = AiBaseInfoConfig.getDocumentSplitUrl();
            System.out.println(AiBaseInfoConfig.getMinerUUrl());
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(documentSplitUrl);
            httpPost.setHeader("Content-Type", "application/json; utf-8");
            httpPost.setHeader("Authorization", "Bearer " + AiBaseInfoConfig.getDocumentSplitKey());
            String string = getString(template);
            // 创建参数列表
            if (StringUtils.isNotBlank(string)) {
                httpPost.setEntity(new StringEntity(string, ContentType.create("application/json", "UTF-8")));
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error("【请求失败】原因：{}", e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }

        // 解析返回结果
        JSONObject jsonObject = JSONObject.parseObject(resultString);
        Object result = jsonObject.get("result");
        if (result == null) {
            throw new RuntimeException("文本切割返回结果为空");
        }
        // 获取切块
        JSONObject resultJson = JSONObject.from(result);
        JSONArray chunks = resultJson.getJSONArray("chunks");
        //将返回的切块都变成jsonObject
        return chunks.toJavaList(JSONObject.class);
    }

    private static String getString(String template) {
        JSONObject jsonObject = new JSONObject();
        JSONObject document = new JSONObject();
        document.put("content", template);
        jsonObject.put("document", document);
        document.put("content_type", "markdown");
        JSONObject strategy = new JSONObject();
        strategy.put("type", "default");
        // 按照300token 进行拆分
        strategy.put("max_chunk_size", 300);
        strategy.put("compute_type", "token");
        strategy.put("need_sentence", "false");
        jsonObject.put("strategy", strategy);
        String string = jsonObject.toString();
        return string;
    }
}
